package com.caocaog.market.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.entity.MartResearch;
import com.caocaog.market.entity.MartResearchHis;
import com.caocaog.market.mapper.MartResearchMapper;
import com.caocaog.market.service.MartResearchHisService;
import com.caocaog.market.service.MartResearchService;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 市场调研
 *
 * @author chechen
 * @date 2022-01-13
 */
@Service
@RequiredArgsConstructor
@Transactional(rollbackFor = Exception.class)
public class MartResearchServiceImpl extends ServiceImpl<MartResearchMapper, MartResearch> implements MartResearchService {

    private final MartResearchHisService martResearchHisService;

    @Override
    public IPage<MartResearch> queryMartResearchPage(Page<MartResearch> page, MartResearch martResearch) {
        return super.baseMapper.queryMartResearchPage(page, martResearch);
    }

    @Override
    public MartResearch getMartResearchById(String id) {
        return super.baseMapper.selectById(id);
    }

    @Override
    public String addMartResearch(MartResearch martResearch) {
        martResearch.clearFields();
        martResearch.setCreateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());

        // 新增市场调研
        super.baseMapper.insert(martResearch);
        if (martResearch.getId() == null) {
            throw new JeecgBootException("新增市场调研失败");
        }

        // 新增市场调研历史
        MartResearchHis martResearchHis = new MartResearchHis(martResearch);
        this.martResearchHisService.addMartResearchHis(martResearchHis);

        return martResearch.getId();
    }

    @Override
    public int updateMartResearch(MartResearch martResearch) {
        martResearch.clearFields();
        martResearch.setUpdateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());

        // 更新市场调研
        int updateRecordCount = super.baseMapper.updateById(martResearch);
        if (updateRecordCount == 0) {
            throw new JeecgBootException("更新市场调研失败, id-> " + martResearch.getId());
        }

        // 新增市场调研历史
        MartResearchHis martResearchHis = new MartResearchHis(martResearch);
        this.martResearchHisService.addMartResearchHis(martResearchHis);

        return updateRecordCount;
    }

    @Override
    public int deleteMartResearch(Long id) {
        int deleteRecordCount = super.baseMapper.deleteById(id);

        if (deleteRecordCount == 0) {
            throw new JeecgBootException("删除市场调研失败, id-> " + id);
        }
        return deleteRecordCount;
    }

}
